import Vue from 'vue';
import loadingVue from './Loading.vue';

const LoadingTemplate = Vue.extend(loadingVue);

LoadingTemplate.prototype.close = function() {
  if (this.$el && this.$el.parentNode) {
    this.$el.classList.add('close');
    setTimeout(() => {
      this.$el.parentNode?.removeChild(this.$el);
    }, 300);
  }
  this.$destroy();
};

const herinLoading = (options = {}) => {
  const target = document.querySelector(options.target || 'body');
  const instance = new LoadingTemplate({
    el: document.createElement('div'),
    data: options
  });
  const oldLoading = target.querySelector('.herin-loading');
  oldLoading && target.removeChild(oldLoading);
  target.appendChild(instance.$mount().$el);
  return instance;
};

export default herinLoading;
